import mqtt from "mqtt";
import { uuid } from "@/views/common/js/utils.js";
/*
使用方法
this.client= new initMqtt().connect()
*/

function initMqtt(options) {
  const { url, userName, password } = options || {};
  this.options = {
    //clean: true, //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
    connectTimeout: 5000, // 超时时间
    reconnectPeriod: 5000, // 重连时间间隔
    clientId: "mqttjs_" + uuid(), //clientId随机防止冲突掉线
    username: userName,
    password: password
  };
  this.connectUrl = url;
}

initMqtt.prototype.connect = function(onSuccess) {
  try {
    this.client = mqtt.connect(this.connectUrl, this.options);
  } catch (error) {
    console.log("mqtt连接异常", error);
  }
  this.client.on("connect", () => onSuccess());
  this.client.on("error", error => {
    console.error("mqtt连接异常", error);
  });
  this.client.on("reconnect", () => {
    console.info("mqtt正在重连");
  });
  this.client.on("disconnect", error => {
    console.info("mqtt服务器断开:", error);
  });
  return this.client;
};
initMqtt.prototype.disconnect = function() {
  if (this.client) {
    this.client.end();
    this.client = null;
  }
};

export default initMqtt;
